// src/main/java/com/example/musicplayer/SongAdapter.kt
package com.example.musicplayer

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.musicplayer.model.Song
import java.util.*
import android.graphics.BitmapFactory

class SongAdapter(private var songs: List<Song>, private val listener: OnItemClickListener) :
    RecyclerView.Adapter<SongAdapter.SongViewHolder>() {

    interface OnItemClickListener {
        fun onItemClick(song: Song)
    }

    class SongViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val imageViewSong: ImageView = itemView.findViewById(R.id.imageViewSong)
        val textViewTitle: TextView = itemView.findViewById(R.id.textViewTitle)
        val textViewArtist: TextView = itemView.findViewById(R.id.textViewArtist)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SongViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_song, parent, false)
        return SongViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: SongViewHolder, position: Int) {
        val currentSong = songs[position]
        holder.textViewTitle.text = currentSong.title
        holder.textViewArtist.text = currentSong.artist

        // 将 BLOB 转换为 Bitmap 并显示在 ImageView 中
        currentSong.image?.let { bytes ->
            val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
            holder.imageViewSong.setImageBitmap(bitmap)
        } ?: run {
            // 如果没有图片，可以设置一个默认图片
            holder.imageViewSong.setImageResource(R.drawable.logo)
        }

        holder.itemView.setOnClickListener {
            listener.onItemClick(currentSong)
        }
    }

    override fun getItemCount(): Int {
        return songs.size
    }

    fun updateData(newSongs: List<Song>) {
        songs = newSongs
        notifyDataSetChanged()
    }
}